home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 1996 19:20:47 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601201820.AA01752@dxmint.cern.ch>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: frigate.doc.ic.ac.uk!dxmint.cern.ch!hpl3sn03.cern.ch
-
- ebennett@rust.net writes:
-
- >Given some number, there is a neat trick to generate a mask which will
- >have exactly one bit set in it. The bit set will be the least
- >significant non-zero bit in the original number:
- >
- > mask = ~number & number;
- >
- >Now, if number contained a single non-zero bit (and is therefore a
- >power of 2), mask will be equal to number. Therefore:
- >
- > if (number == (~number & number))
- > {
- > /* number is a power of 2 */
- > }
- >
- >Try it, you'll like it!
-
- I don't think so. ~number & number will _always_ give 0. -number & number
- will actually work, except for the case when number == 0. That is,
- assuming a two's complement implementation. On a one's complement or
- sign-magnitude implementation it won't work at all.
-
- Yet another guy who makes a fool of himself because he's too lazy to
- test his solution before posting.
-
- Dan
-